import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  OnInit,
  ViewChild,
  AfterViewInit,
  OnDestroy,
  Renderer2
} from '@angular/core'
import {
  assetsInfoObject,
  AuthGuardService,
  SourceType
} from '../@core/auth-guard-service.guard'
import { TranslateService } from '@ngx-translate/core'
import { LoadingService } from 'ng-devui/loading'
import { TableWidthConfig, SortDirection } from 'ng-devui/data-table'
import { DialogService } from 'ng-devui/modal'
import { DocumentRef } from 'ng-devui/window-ref'
import { AssetsDetailComponent } from './assets-detail/assets-detail.component'

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-blockchain',
  templateUrl: './blockchain.component.html',
  styleUrls: ['./blockchain.component.less']
})
export class BlockchainComponent implements OnInit, AfterViewInit, OnDestroy {
  showLoading: boolean = false //表格加载数据时是否添加遮罩层
  sLoading: any
  total: number = 40 //表格数据总量
  next: number = 1 //查询索引
  complete: boolean = false //是否完成查询
  lazyDataSource: Array<SourceType> = []
  i18nValues: any //国际化变量
  assetsQueryTitle: string = '' //藏品查询标题
  assetsNum: string = '' //藏品编号
  sexTypePholder: string = '' //集合名称placeholder
  sexTypeTitle: string = '' //集合名称
  assetInfos: assetsInfoObject[] //藏品详情信息
  assetsRunList: assetsInfoObject[]
  assetsTopTitle: string = ''
  dataTableOptions = {
    columns: [
      {
        field: '',
        header: '',
        fieldType: ''
      },
      {
        header: '',
        field: '',
        fieldType: ''
      },
      {
        field: '',
        header: '',
        fieldType: ''
      }
    ]
  }
  time: string | number = 0
  blockChainCount: string | number = 0
  transactionsCount: string | number = 0
  isShowSearchDetail: boolean = false //是否显示搜索详情弹框
  timer: any = null
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'block_id',
      width: '100px'
    },
    {
      field: 'time',
      width: '100px'
    },
    {
      field: 'tx_id',
      width: '160px'
    }
  ]
  _totalWidth = 0
  lastWidth = 0
  firstResize = true
  searchText: string = ''
  searchEle: any
  blockIdSortDirection = SortDirection.ASC
  txIdSortDirection = SortDirection.default
  timeSortDirection = SortDirection.default
  sortParams: any
  scrollTop: number
  illegalReg: RegExp = /[^a-zA-Z\d#]/g
  COLLECTION_ID_REX: RegExp =
    /((^8e848d51008c3d6b17f71671)|(^78b773578e12b0914d3faffd))[#]?[0-9]{1,5}$/
  @ViewChild('searchResult', { read: ElementRef }) searchResult: ElementRef

  constructor(
    private cdr: ChangeDetectorRef,
    private translate: TranslateService,
    private authGuardService: AuthGuardService,
    private dialogService: DialogService,
    private documentRef: DocumentRef,
    private renderer: Renderer2
  ) { }

  ngOnInit() {
    this.i18nValues = this.translate.instant('blockchain')
    this.initBlockchainData()
    this.queryBlockchainSummaryInfo()
    this.dataTableOptions = {
      //表格数据
      columns: [
        {
          field: 'block_id',
          header: this.i18nValues['block']['no'],
          fieldType: 'text'
        },
        {
          field: 'time',
          header: this.i18nValues['assets']['createTime'],
          fieldType: 'text'
        },
        {
          field: 'tx_id',
          header: this.i18nValues['block']['id'],
          fieldType: 'text'
        }
      ]
    }
    this.assetsRunList = [
      {
        name: this.i18nValues['pageTitle'][4],
        value: ''
      },
      {
        name: this.i18nValues['pageTitle'][5],
        value: ''
      },
      {
        name: this.i18nValues['pageTitle'][6],
        value: ''
      }
    ]
    this.searchEle = document.querySelector('.devui-search .devui-input')
      ; (window as any).onPageView('')
  }

  initBlockchainData() {
    this.assetsNum = this.i18nValues['assetsNum']
    this.sexTypeTitle = this.i18nValues['sexTypeTitle']
    this.sexTypePholder = this.i18nValues['sexTypePholder']
    this.assetsQueryTitle = this.i18nValues['assetsQueryTitle']
    this.assetsTopTitle = this.i18nValues['assets']['assetsTopTitle']
    this.assetInfos = [
      {
        name: this.i18nValues['assets']['title'],
        value: ''
      },
      {
        name: this.i18nValues['assets']['owner'],
        value: ''
      },
      {
        name: this.i18nValues['assets']['getTime'],
        value: ''
      },
      {
        name: this.i18nValues['block']['title'],
        value: ''
      },
      {
        name: this.i18nValues['block']['id'],
        value: ''
      },
      {
        name: this.i18nValues['block']['no'],
        value: ''
      }
    ]
  }

  ngAfterViewInit(): void { }

  //查询藏品链上详情
  searchAssetsDetail() {
    ; (window as any).onEvent('查询藏品详情', 'click', '查询藏品详情', '')
    this.authGuardService
      .queryAssetsDetail(this.searchText)
      .subscribe((res) => {
        if (res.code == '0') {
          this.assetInfos[1].value = res.data.owner
          this.assetInfos[2].value = this.authGuardService.formatDate(
            res.data.time
          )
          this.assetInfos[4].value = res.data.tx_id
          this.assetInfos[5].value = res.data.block_id
          //刷新页面数据
          this.cdr.markForCheck()
          this.openStandardDialog('standard')
        } else {
          this.authGuardService.showModalPanel('warning', res.msg).then(() => {
            this.searchText = ''
          })
        }
      })
  }

  getSearchKeyword(v) {
    if (v) {
      this.searchText = v.replace(this.illegalReg, '')
      this.searchEle.value = this.searchText
    } else {
      this.searchText = ''
    }
  }

  //处理搜索关键字
  verifySearchKeyword() {
    if (this.searchText) {
      this.searchAssetsDetail()
    } else {
      this.authGuardService.showModalPanel(
        'warning',
        this.i18nValues['panelText'][1]
      )
    }
  }

  queryRecentTransactionCount() {
    this.authGuardService
      .queryRecentTransactionCount('10')
      .subscribe((succRes) => {
        if (Array.isArray(succRes.data) && succRes.data.length) {
          this.lazyDataSource = JSON.parse(JSON.stringify(succRes.data))
          this.lazyDataSource = this.lazyDataSource.splice(0, 10)
          //刷新页面数据
          this.cdr.markForCheck()
        }
      })
  }

  assetsRunTime() {
    const INITTIMESTAMP = new Date(this.time).getTime()
    const CURRTIMESTAMP = new Date().getTime()
    const TIMEDIFFSECOND = (CURRTIMESTAMP - INITTIMESTAMP) / 1000
    const DAYS = parseInt(String(TIMEDIFFSECOND / (60 * 60 * 24)))
    const REMAINSECOND = TIMEDIFFSECOND % (60 * 60 * 24)
    const HOURS = parseInt(String(REMAINSECOND / (60 * 60)))
    const REMAINSECOND2 = REMAINSECOND % (60 * 60)
    const MINS = parseInt(String(REMAINSECOND2 / 60))
    const TIME = DAYS + '天' + HOURS + '小时' + MINS + '分钟'
    this.assetsTopTitle = this.i18nValues['assets']['assetsTopTitle']
      .replace('{0}', `<span style="font-weight:600;">${TIME}</span>`)
      .replace(
        '{1}',
        `<span style="font-weight:600;">${this.blockChainCount}</span>`
      )
      .replace(
        '{2}',
        `<span style="font-weight:600;">${this.transactionsCount}</span>`
      )
    this.assetsRunList[0].value = TIME
    this.assetsRunList[1].value = this.blockChainCount as string
    this.assetsRunList[2].value = this.transactionsCount as string
    clearInterval(this.timer)
    this.timer = setInterval(() => {
      this.assetsRunTime()
    }, 1000 * 60)
    this.cdr.markForCheck()
  }

  queryBlockchainSummaryInfo() {
    this.authGuardService.queryBlockchainSummaryInfo().subscribe((succRes) => {
      if (Object.keys(succRes).length) {
        this.time = succRes.data?.starttime || 0
        this.blockChainCount = succRes.data?.blocks || 0
        this.transactionsCount = succRes.data?.txs || 0
        this.assetsRunTime()
      }
      this.queryRecentTransactionCount()
    })
  }

  ngOnDestroy() {
    clearInterval(this.timer)
    this.timer = null
  }

  openStandardDialog(dialogtype?: string) {
    this.setHtmlStyle()
  }
  
  setHtmlStyle() {
    this.scrollTop = this.documentRef.documentElement.scrollTop
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'position',
      'fixed'
    )
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'top',
      `-${this.scrollTop}px`
    )
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'overflow-y',
      `scroll`
    )
    this.renderer.setStyle(this.documentRef.documentElement, 'width', `100%`)
  }

  removeHtmlStyle() {
    this.renderer.removeStyle(this.documentRef.documentElement, 'position')
    this.renderer.removeStyle(this.documentRef.documentElement, 'width')
    this.renderer.removeStyle(this.documentRef.documentElement, 'overflow')
    this.renderer.removeStyle(this.documentRef.documentElement, 'top')
    this.documentRef.documentElement.scrollTop = this.scrollTop
  }

  openDialog(dialogtype?: string, content?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '600px',
      maxHeight: '600px',
      backdropCloseable: true,
      dialogtype: dialogtype,
      content: content,
      buttons: [
        {
          cssClass: 'primary',
          text: '关闭',
          disabled: false,
          handler: () => {
            results.modalInstance.hide()
          }
        }
      ]
    })
  }
}
